

//
//  CPJFriendViewController.swift
//  Sina
//
//  Created by YYY on 2017/8/10.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

class CPJFriendViewController: CPJBaseViewController {

    var demoLabel: UILabel = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let model = EmotionManager.shared.emoticonManager(string: "[马上有对象]")
        
        let tempLabel = UILabel(frame: CGRect(x: 30, y: 100, width: 320, height: 100))
        tempLabel.font = UIFont.systemFont(ofSize: 20)
        
        tempLabel.attributedText = model?.imageText(font: tempLabel.font)
        view.addSubview(tempLabel)
        tempLabel.attributedText = EmotionManager.shared.emoticonString(string: "我[笑哈哈]哎[马上有对象]五月来了[霹雳]", font: tempLabel.font)
        demoLabel = tempLabel
        // Do any additional setup after loading the view.
    }

    
    /// 图文字符串
    ///
    /// - Parameter string: 完整字符串
    /// - Returns: 属性文本
    func emoticonString(string: String) -> NSMutableAttributedString
    {
        let attributedString = NSMutableAttributedString(string: string)
        
        // "我[笑哈哈]哎[马上有对象]"
        //建立正则表达式，过滤所有的表情和文字
        //[] ()都是正则表达式的关键字，如果参与匹配，需要转义
        let pattern = "\\[.*?\\]"
        
        guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else
        {
            return attributedString
        }
        
        //匹配所有项
        let matches = regx.matches(in: string, options: [], range: NSRange(location: 0, length: attributedString.length))
        
        for match in matches.reversed()
        {
            let range = match.rangeAt(0)
            
            let subString = (attributedString.string as NSString).substring(with: range)
            
            if let model = EmotionManager.shared.emoticonManager(string: subString)
            {
                attributedString.replaceCharacters(in: range, with: model.imageText(font: demoLabel.font))
            }
    
           
        }
        return attributedString
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
